/**
 * @des 整合目前el-table拖拽之后保存宽度的共用方法
 */
import { storageSet, storageGet } from '@src/util/storageV2';
export default {
  methods: {
    /**
     * @des 表单拖拽钩子函数
     */
    headerDragend(newWidth, oldWidth, column, event) {
      let data = this.columns
        .map((item) => {
          if (
            item.fieldName === column.property
            || item.field === column.property
          ) {
            item.width = column.width;
          }
          return item;
        })
        .map((item) => {
          return {
            field: item.field,
            show: item.show,
            width: item.width,
          };
        });
      this.modifyColumnStatus({ type: 'column', data });
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    modifyColumnStatus(event) {
      let columns = event.data || [],
        colMap = columns.reduce(
          (acc, col) => (acc[col.field] = col) && acc,
          {}
        );
      this.columns.forEach((col) => {
        let newCol = colMap[col.field];
        if (null != newCol) {
          this.$set(col, 'show', newCol.show);
          this.$set(col, 'width', newCol.width);
        }
      });

      this.saveColumnStatusToStorage();
    },

    saveColumnStatusToStorage() {
      const localStorageData = this.getLocalStorageData();
      let columnsStatus = null;

      // 判断是否存储选择列
      const columnsList = this.columns.map((c) => ({
        field: c.field,
        show: c.show,
        width: c.width,
      }));

      if (localStorageData.columnStatus) {
        localStorageData.columnStatus[
          `${this.selectColumnState}`
        ] = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = {
          [`${this.selectColumnState}`]: columnsList,
        };
      }

      this.saveDataToStorage('columnStatus', columnsStatus);
    },
    getLocalStorageData() {
      const dataStr = storageGet('customerListData') || '{}';
      return JSON.parse(dataStr);
    },
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      storageSet('customerListData', JSON.stringify(data));
    },
  },
};
